package com.service.serviceImpl;

import com.entity.PostsEntity;
import com.mapper.PostsMapper;
import com.service.PostsService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

public class PostsServiceImpl implements PostsService {
    public List<PostsEntity> postsList() throws IOException {
        String resource = "/mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PostsMapper mapper = sqlSession.getMapper(PostsMapper.class);
        return mapper.postsList();
    }

    public boolean insertPosts(PostsEntity postsEntity) throws IOException {
        String resource = "/mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PostsMapper mapper = sqlSession.getMapper(PostsMapper.class);
        boolean b = mapper.insertPosts(postsEntity);
        sqlSession.commit();
        return b;
    }

    public PostsEntity getBypostsId(String id) throws IOException {
        String resource = "/mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PostsMapper mapper = sqlSession.getMapper(PostsMapper.class);
        return mapper.getBypostsId(id);
    }

    public PostsEntity testPostUser(String id) throws IOException {
        String resource = "/mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PostsMapper mapper = sqlSession.getMapper(PostsMapper.class);
        return mapper.testPostUser(id);
    }
}
